package controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Auther:ws@itany.com
 * Date:20-9-18 上午10:41
 * Version:1.0
 * Description:
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/showUpload")
    public String showUpload (){
        return "upload";
    }

    @RequestMapping("/upload")
    public void upload(String username, CommonsMultipartFile file, HttpSession session) throws IOException {
//        String path = session.getServletContext().getRealPath("/upload/"+new SimpleDateFormat("yyyyMMdd").format(new Date()));
//        File f = new File(path);
//        f.mkdirs();
//        file.transferTo(new File(path,file.getOriginalFilename()));
        String path = session.getServletContext().getRealPath("/upload" + new SimpleDateFormat("yyyyMMdd").format(new Date()));
        File f = new File(path);
        f.mkdirs();
        file.transferTo(new File(path,file.getOriginalFilename()));
    }



    @RequestMapping("/showDownload")
    public String showDownload(){
        return "download";
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(HttpSession session) throws IOException {
        String path = session.getServletContext().getRealPath("images/111.png");
        File file = new File(path);

        //设置头信息
        HttpHeaders headers = new HttpHeaders();

        // 参数一:表示当前所使用的MIME协议方式,即下载的方式
        // 其值有两种
        //  1.attachment:以附件的方式进行下载
        //  2.inline:在线打开
        // 参数二:下载时所显示的文件名
        headers.setContentDispositionFormData("inline","hahaha将撒h");
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);

    }
}
